package com.os.sys.common.filter;

import com.os.sys.common.utility.DateClass;
import com.os.sys.common.utility.PubClass;
import com.os.sys.common.utility.WebClass;
import com.os.sys.model.ILoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/1/12.
 * 全局自动日志记录
 */
@Aspect
@Component
public class FilterLog {
    @Resource
    private PubClass pubClass;

    //REVIEW 这个拦截和SysAuth的拦截一样，会无效。以后考虑整合这2个方法到一起
    @Pointcut("execution(* com.os.*.controller..*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void getLog(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        HttpServletRequest request = WebClass.getRequest();

        StringBuilder sb = new StringBuilder();
        sb.append("\n-------------------------begin:" + DateClass.getCurDate() + "-------------------------");

        ILoginUser loginuser = pubClass.getLoginUser();
        if (loginuser != null) {
            sb.append("\nUSERNAME ==> ").append(loginuser.getLoginUserName());
        }

        sb.append("\nHOST ==> ").append(WebClass.getHost());
        sb.append("\nURL ==> ").append(request.getRequestURL().toString());
        sb.append("\nHTTP_METHOD ==> ").append(request.getMethod());
        sb.append("\nIP ==> ").append(WebClass.getIP());
        sb.append("\nCLASS_METHOD ==> ").append(joinPoint.getSignature().getDeclaringTypeName()).append(".").append(joinPoint.getSignature().getName());
        //sb.append("ARGS : " + Arrays.toString(joinPoint.getArgs()));


        Enumeration<String> enu = request.getParameterNames();
        StringBuilder sbParams = new StringBuilder();
        while (enu.hasMoreElements()) {
            String paraName = enu.nextElement();
            sbParams.append("\n" + paraName).append(": ").append(request.getParameter(paraName));
        }

        sb.append("\nPARAMS ==> ").append(sbParams.toString());
        sb.append("\n-------------------------end:" + DateClass.getCurDate() + "-------------------------");
        //REVIEW 本来想读取request的body，发现java如果提前读取body，会导致接下来无法给真正的controller读取到body
        //       传闻解决方案按，读取完后，重写一次body回去

        pubClass.showLog(sb.toString());
    }

//    @AfterReturning(returning = "ret", pointcut = "webLog()")
//    public void doAfterReturning(Object ret) throws Throwable {
//        // 处理完请求，返回内容
//        logger.info("RESPONSE : " + ret);
//    }

}
